package com.zc.msmservice.controller;

import com.zc.msmservice.service.MsmService;
import com.zc.msmservice.utils.RandomUtil;
import com.zc.servicebase.exception.CongException;
import com.zc.utils.R;
import com.zc.utils.ResultStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm")
@CrossOrigin
public class MsmController {

	@Autowired
	private MsmService msmService;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@GetMapping("send/{phone}")
	public R sendMsm(@PathVariable String phone) {
		// 从redis获取验证码，获取到返回，获取不到再发送，
		String code = redisTemplate.opsForValue().get(phone);
		if (!StringUtils.isEmpty(code)) {
			throw new CongException(ResultStatus.ERROR, "您的验证码还在有效期内，请不要重复发送验证");
		}

		code = RandomUtil.getFourBitRandom();
		Map map = new HashMap<String, String>();
		map.put("code", code);
		boolean isSend = msmService.send(map, phone);
		if (isSend) {
			redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
			return R.ok();
		}
		return R.error();
	}
}
